from pyecharts import options as opts
from pyecharts.charts import Line, Bar
import datetime

import datas_fetch


# 所有设备的平均开机率（七天）
def start_rate():
    TimeInfos_mean = round(
        datas_fetch.TimeInfos.groupby(by='datetime', sort=True, as_index=False).agg({'startrate': 'mean'}),
        2)  # 聚合求平均值匹配
    date = (datetime.datetime.strptime(datas_fetch.TimeInfos['datetime'].max(), '%Y-%m-%d') + datetime.timedelta(
        days=-7)).strftime('%Y-%m-%d')
    timeinfo = TimeInfos_mean[TimeInfos_mean['datetime'] >= date]
    date_list = timeinfo['datetime'].tolist()  # 转变成列表
    startRate_list = timeinfo['startrate'].tolist()

    line = Line(init_opts=opts.InitOpts(width='100%', height='420px'))
    line.add_xaxis([i[5:] for i in date_list])  # 切取时间
    line.add_yaxis("", startRate_list, color='#33ffff')
    line.set_global_opts(
        title_opts=opts.TitleOpts(title='所有设备的平均开机率（七天）', title_textstyle_opts={"color": "white"}),  # 主标题
        # Y的设置
        yaxis_opts=opts.AxisOpts(
            name="开机率(%)", axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))),
        # X的设置
        xaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white")))  # 线的样式
    )
    line.set_series_opts(
        label_opts=opts.LabelOpts(color='white')  # 系列配置项
    )
    return line


# 设备工作时长前十名
def workTime_top():
    top = datas_fetch.day_timeinfos.sort_values(by='worktime', ascending=False).head(10)
    equipMentNumber_list = top['equipmentnumber'].tolist()
    workTime_list = top['worktime'].tolist()
    bar = Bar(init_opts=opts.InitOpts(width='100%', height='420px'))
    bar.add_xaxis(equipMentNumber_list)
    bar.add_yaxis("", workTime_list, color='#33ffff', category_gap=10)
    bar.set_global_opts(
        title_opts=opts.TitleOpts(title='设备工作时长前十名', title_textstyle_opts={"color": "white"}),
        yaxis_opts=opts.AxisOpts(
            max_=24, name='时长', axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))),
        xaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(rotate=15, color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))
        )
    )
    bar.set_series_opts(label_opts={"color": "white"})
    return bar


# 所有设备工作时间统计
def workTime_count():
    workTime_mean = round(datas_fetch.day_timeinfos['worktime'].mean(), 2)
    higher = 0; lower = 0; count = 0;
    for i in datas_fetch.day_timeinfos['worktime']:
        if i < workTime_mean:
            lower += 1
        else:
            higher += 1
        count += 1
    bar = Bar(init_opts=opts.InitOpts(width='100%', height='420px'))
    bar.add_xaxis(xaxis_data=['总', '低', '高'])
    bar.add_yaxis("总设备数量", y_axis=[count, 0, ], category_gap=5, itemstyle_opts=opts.ItemStyleOpts(color='#33ffff'))
    bar.add_yaxis("低于平均工作时长设备数", y_axis=[0, lower, ], category_gap=5,
                  itemstyle_opts=opts.ItemStyleOpts(color='#9999ff'))
    bar.add_yaxis("高于平均工作时长设备数", y_axis=[0, 0, higher], category_gap=5,
                  itemstyle_opts=opts.ItemStyleOpts(color='#33ff99'))
    bar.set_global_opts(title_opts=opts.TitleOpts('所有设备工作时间统计', title_textstyle_opts={"color": "white"}),
        legend_opts=opts.LegendOpts(
            is_show=True, pos_right='5', pos_top='20', orient='vertical', item_width=5,
            textstyle_opts=opts.TextStyleOpts(font_size=10, color="white"),
        ),
        xaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))
        ),
        yaxis_opts=opts.AxisOpts(
            axislabel_opts=opts.LabelOpts(color="white"),
            axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color="white"))
        )
    )
    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    bar.reversal_axis()
    return bar
